<?php
/**
 * Created by PhpStorm.
 * User: server
 * Date: 2019/5/27
 * Time: 15:37
 */

namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path'), EXT);

use app\admin\Controller;
use think\Db;
use think\Config;
use think\Request;

class DriverPrepayment extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $data = input();
        $map = [];

        if (!empty($data['group_id'])) {
            $map['dp.group_id'] = ['=', $data['group_id']];
        }

        if (!empty($data['title'])) {
            $map['r.title'] = ['like', "%{$data['title']}%"];
        }

        if (!empty($data['realname'])) {
            $map['au.realname'] = ['like', "%{$data['realname']}%"];
        }

        if (!empty($data['car_type'])) {
            $map['d.car_type'] = ['like', "%{$data['car_type']}%"];
        }

        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");

        $list = Db::name('driver_prepayment')
            ->alias('dp')
            ->join('tp_dispatch_traveler_group dtg', 'dtg.id=dp.group_id', 'left')
            ->join('tp_route r', 'r.id=dtg.route_id', 'left')
            ->join('tp_driver d', 'd.user_id=dtg.driver_user_id', 'left')
            ->join('tp_car_model cm','d.car_model_id=cm.id','left')
            ->join('tp_admin_user au', 'au.id=dtg.driver_user_id', 'left')
            ->field('dp.*,dtg.go_date,dtg.route_id,dtg.driver_user_id,dtg.prepaid_expenses,dtg.end_gauge_value,dtg.end_odometer_value,r.title,r.day,d.car_type,au.realname,dtg.start_gauge_value,dtg.start_odometer_value,cm.oil_consumption')
            ->where($map)
            ->order('dp.id desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        $new_list = $list->toArray()['data'];

        // 获取发票费用
        foreach ($new_list as $k => $v) {
            $new_list[$k]['invoice'] = Db::name('driver_invoice')
                ->where('dispatch_group_id', $v['group_id'])
                ->where('isdelete',0)
                ->select();

            $new_list[$k]['oil_cost'] = 0;
            $new_list[$k]['rests_cost'] = 0;
            $new_list[$k]['parking_fee'] = 0;
            $new_list[$k]['car_washing_fee'] = 0;
            $new_list[$k]['road_toll'] = 0;
            foreach ($new_list[$k]['invoice'] as $k2 => $v2) {
                switch ($v2['invoice_type']) {
                    case '加油费':
                        $new_list[$k]['oil_cost'] = $v2['total'];
                        break;
                    case '停车费':
                        $new_list[$k]['parking_fee'] = $v2['total'];
                        break;
                    case '洗车费':
                        $new_list[$k]['car_washing_fee'] = $v2['total'];
                        break;
                    case '过路费':
                        $new_list[$k]['road_toll'] = $v2['total'];
                        break;
                    default:
                        $new_list[$k]['rests_cost'] = $v2['total'] + $new_list[$k]['rests_cost'];
                        break;
                }
            }
        }

        $this->view->assign('list', $new_list);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());

        return $this->view->fetch();
    }

    /**
     * 电子表格
     * @return mixed
     */
    public function get_excel(Request $request)
    {
        $data = input();
        ini_set('max_execution_time', 3600);//1小时
        ini_set('memory_limit', '500M');
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel, 'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l + 65);
        }

        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j] . $letter[$k];
            }
        }
        $tableHeader = ['派车单号', '出行日期', '线路名称', '天数', '实际打款', '预支付标准', '司机', '车型', '起始油表数', '结束油表数', '起始里程数','结束里程数','报销','抵消','备注','过路费','加油费','停车费','洗车费','其他','预计油耗量','实际油耗量'];
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++) {
            $export_sheet->setCellValue("$letter[$i]1", "$tableHeader[$i]");
            $export_sheet->getColumnDimension("$letter[$i]")->setWidth(20);
        }

        $map = array();

        //选择导出数据
        if ($data['id']) {
            $id = implode($data['id'], ',');
            $map['dp.id'] = ['in', $id];
        }

        if (!empty($data['group_id'])) {
            $map['dp.group_id'] = ['=', $data['group_id']];
        }

        if (!empty($data['title'])) {
            $map['r.title'] = ['like', "%{$data['title']}%"];
        }

        if (!empty($data['realname'])) {
            $map['au.realname'] = ['like', "%{$data['realname']}%"];
        }

        if (!empty($data['car_type'])) {
            $map['d.car_type'] = ['like', "%{$data['car_type']}%"];
        }

        $list = Db::name('driver_prepayment')
            ->alias('dp')
            ->join('tp_dispatch_traveler_group dtg', 'dtg.id=dp.group_id', 'left')
            ->join('tp_route r', 'r.id=dtg.route_id', 'left')
            ->join('tp_driver d', 'd.user_id=dtg.driver_user_id', 'left')
            ->join('tp_car_model cm','d.car_model_id=cm.id','left')
            ->join('tp_admin_user au', 'au.id=dtg.driver_user_id', 'left')
            ->field('dp.group_id,dtg.go_date,r.title,r.day,dp.actual_money,dtg.prepaid_expenses,au.realname,d.car_type,dtg.start_gauge_value,dtg.end_gauge_value,dtg.start_odometer_value,dtg.end_odometer_value,dp.reimbursement,dp.offset,dp.remark,cm.oil_consumption')
            ->where($map)
            ->order('dp.id desc')
            ->select();

        foreach ($list as $k => $v) {
            $driver_invoice_list = Db::name('driver_invoice')
                ->where('dispatch_group_id', $v['group_id'])
                ->where('isdelete',0)
                ->select();

            $list[$k]['oil_cost'] = 0;
            $list[$k]['parking_fee'] = 0;
            $list[$k]['car_washing_fee'] = 0;
            $list[$k]['road_toll'] = 0;
            $list[$k]['rests_cost'] = 0;

            foreach ($driver_invoice_list as $k2 => $v2) {
                switch ($v2['invoice_type']) {
                    case '加油费':
                        $list[$k]['oil_cost'] = $v2['total'];
                        break;
                    case '停车费':
                        $list[$k]['parking_fee'] = $v2['total'];
                        break;
                    case '洗车费':
                        $list[$k]['car_washing_fee'] = $v2['total'];
                        break;
                    case '过路费':
                        $list[$k]['road_toll'] = $v2['total'];
                        break;
                    default:
                        $list[$k]['rests_cost'] = $v2['total'] + $list[$k]['rests_cost'];
                        break;
                }
            }
            $list[$k]['expect'] = ($v['oil_consumption']/100)*($v['end_odometer_value']-$v['start_odometer_value']);
            $list[$k]['practical'] = $v['end_gauge_value'] - $v['start_gauge_value'];

            unset($list[$k]['oil_consumption']);

        }

        if (!empty($list)) {
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);
                }

            }
        }

        //定义table键
        if (!empty($list)) {
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);
                }
            }
        }

        $fileName = date('YmdHis', time()) . "司机发票统计-司机发票统计数据.xls";
        $fileName = iconv('utf-8', 'gb2312', $fileName);
        ob_end_clean();
        if ($request->isGet()) {
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename=' . $fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        } else {
            // 保存文件到服务器上
            $path = ROOT_PATH . "public/excel";
            // 判断文件是否存在
            if (!file_exists($path)) {
                mkdir($path, 0777, true);
            }
            $fileName = iconv('gb2312', 'utf-8', $fileName);
            $file = $path . "/{$fileName}";
            $writer->save($file);
            $url = $request->domain() . "/excel/{$fileName}";
            return ajax_return_adv($url, '', '', '', '', '', 5);
        }
    }
}